package cn.itcast.es.web;

import cn.itcast.es.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author 虎哥
 */
@Slf4j
@RestController
@RequestMapping("hello")
public class HelloController {

    @GetMapping("sync")
    public User queryUserSync(){
        log.warn("sync 开始查询用户");
        User user = createUser();
        log.warn("sync 结束查询用户");
        return user;
    }

    @GetMapping("mono")
    public Mono<User> queryUserMono(){
        log.warn("sync 开始查询用户");
        Mono<User> mono = Mono.fromSupplier(this::createUser);
        log.warn("sync 结束查询用户");
        return mono;
    }

    @GetMapping("flux")
    public Flux<User> queryUserFlux(){
        log.warn("flux 开始查询用户");
        Flux<User> flux = createUserFlux();
        log.warn("flux 结束查询用户");
        return flux;
    }

    @GetMapping(value = "stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> queryUserFluxStream(){
        log.warn("stream 开始查询用户");
        Flux<User> flux = createUserFlux();
        log.warn("stream 结束查询用户");
        return flux;
    }

    public Flux<User> createUserFlux(){
        return Flux.interval(Duration.ofSeconds(1))
                .map(Long::intValue)
                .map(i -> User.of("user_" + i, 20 + i))
                ;
    }


    /**
     * 模拟了service的 阻塞业务
     * @return 用户
     */
    public User createUser(){
        User user = User.of("Jack", 21);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return user;
    }
}
